<template>
  <div class="userdetails-page-new">
    <van-nav-bar 
      title="完善信息" 
      left-arrow 
      @click-left="onBack" 
      fixed 
      placeholder
      :border="false"
      :safe-area-inset-top="true"
    />
    <div class="profile-card">
      <div class="avatar-center">
        <img v-if="avatar" :src="avatar" class="avatar-img" />
        <div v-else class="avatar-placeholder">+</div>
        <van-uploader :after-read="onAvatarRead" :max-count="1" accept="image/*" :show-upload="false" class="avatar-uploader-btn">
          <van-button size="small" type="primary" class="avatar-upload-btn">更换头像</van-button>
        </van-uploader>
      </div>
      <van-field v-model="username" label="昵称" placeholder="请输入昵称" clearable class="profile-field" />
      <van-field v-model="birthday" label="出生日期" placeholder="请选择出生日期" readonly @click="showDatePicker = true" class="profile-field" />
      <van-popup v-model:show="showDatePicker" position="bottom">
        <van-date-picker v-model="datePickerValue" title="选择出生日期" @confirm="onDateConfirm" @cancel="showDatePicker = false" :min-date="minDate" :max-date="maxDate" />
      </van-popup>
      <div class="profile-field">
        <div class="field-label">性别</div>
        <div class="gender-card-group">
          <div :class="['gender-card', gender==='男' ? 'selected' : '', genderLocked ? 'locked' : '']" @click="selectGender('男')">
            <span class="gender-icon">👦</span>
            男生
          </div>
          <div :class="['gender-card', gender==='女' ? 'selected' : '', genderLocked ? 'locked' : '']" @click="selectGender('女')">
            <span class="gender-icon">👧</span>
            女生
          </div>
        </div>
        <div v-if="genderLocked" class="gender-tip">*性别设置后不可更改</div>
      </div>
      <van-field v-model="height" label="身高(CM)" placeholder="请输入身高" type="number" clearable class="profile-field" @input="calcBMI" />
      <van-field v-model="weight" label="体重(KG)" placeholder="请输入体重" type="number" clearable class="profile-field" @input="calcBMI" />
      <van-field :model-value="bmi" label="体重指数" readonly input-align="right" class="profile-field" />
      <van-button block type="primary" class="save-btn" @click="handleSave">保存资料</van-button>
    </div>
    
    <van-overlay :show="showLoading" class="loading-overlay">
      <div class="loading-card">
        <div class="loading-icon">
          <van-loading type="spinner" color="#a48fff" size="36px" />
        </div>
        <div class="loading-text">正在保存...</div>
      </div>
    </van-overlay>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
import { db, STORES } from '../utils/db'

const router = useRouter()
const avatar = ref('')
const username = ref('')
const gender = ref('')
const genderLocked = ref(false)
const birthday = ref('')
const height = ref('')
const weight = ref('')
const bmi = ref('')
const showDatePicker = ref(false)
const datePickerValue = ref(['2000', '01', '01'])
const minDate = ref(new Date(1950, 0, 1))
const maxDate = ref(new Date())
const showLoading = ref(false)

onMounted(async () => {
  const userEmail = localStorage.getItem('userEmail')
  if (userEmail) {
    try {
      const user = await db.get(STORES.USER_LIST, userEmail)
      if (user) {
        username.value = user.username || ''
        avatar.value = user.avatar || ''
        gender.value = user.gender || ''
        genderLocked.value = !!user.gender
        birthday.value = user.birthday || ''
        height.value = user.height || ''
        weight.value = user.weight || ''
        bmi.value = user.bmi || ''
        if (user.birthday) {
          const arr = user.birthday.split('-')
          if (arr.length === 3) datePickerValue.value = arr
        }
      }
    } catch (error) {
      console.error('获取用户数据失败:', error)
      showToast('获取用户数据失败')
    }
  } else {
    showToast('请先登录')
    router.push('/login')
  }
})

const onAvatarRead = (file) => {
  if (file.content) {
    avatar.value = file.content
  } else if (file.file) {
    const reader = new FileReader()
    reader.onload = e => {
      avatar.value = e.target.result
    }
    reader.readAsDataURL(file.file)
  }
}

const selectGender = (g) => {
  if (genderLocked.value) {
    showToast('性别设置后不可更改')
    return
  }
  gender.value = g
  genderLocked.value = true
}

const onDateConfirm = (val) => {
  birthday.value = val.selectedValues.join('-')
  showDatePicker.value = false
}

const calcBMI = () => {
  const w = parseFloat(weight.value)
  const h = parseFloat(height.value)
  if (w > 0 && h > 0) {
    bmi.value = ((w / h / h) * 10000).toFixed(2)
  } else {
    bmi.value = ''
  }
}

const validateForm = () => {
  if (!username.value) {
    showToast('请输入昵称')
    return false
  }
  if (!gender.value) {
    showToast('请选择性别')
    return false
  }
  if (!birthday.value) {
    showToast('请选择出生日期')
    return false
  }
  if (!height.value || parseFloat(height.value) <= 0) {
    showToast('请输入有效的身高')
    return false
  }
  if (!weight.value || parseFloat(weight.value) <= 0) {
    showToast('请输入有效的体重')
    return false
  }
  return true
}

const saveUserData = async () => {
  try {
    const userEmail = localStorage.getItem('userEmail')
    if (!userEmail) {
      showToast('请先登录')
      router.push('/login')
      return
    }

    // 获取当前用户数据
    const user = await db.get(STORES.USER_LIST, userEmail)
    if (!user) {
      showToast('用户信息不存在')
      return
    }

    // 更新用户数据
    const updatedUser = {
      ...user,
      username: username.value,
      avatar: avatar.value,
      gender: gender.value,
      birthday: birthday.value,
      height: height.value,
      weight: weight.value,
      bmi: bmi.value
    }

    // 保存到 IndexedDB
    await db.put(STORES.USER_LIST, updatedUser)

    // 只保存基本信息到 localStorage
    localStorage.setItem('userName', username.value)
    localStorage.setItem('userEmail', userEmail)
    
    showToast('保存成功')
    router.back()
  } catch (error) {
    console.error('保存用户数据失败:', error)
    showToast('保存失败，请重试')
  }
}

const handleSave = async () => {
  if (!validateForm()) return
  
  showLoading.value = true
  try {
    await saveUserData()
  } finally {
    showLoading.value = false
  }
}

const onBack = () => {
  router.back()
}
</script>

<style scoped>
.userdetails-page-new {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f6ff 0%, #e9eafc 100%);
  padding-bottom: 16px;
}

.van-nav-bar {
  background: #fff !important;
}

.van-nav-bar :deep(.van-nav-bar__title) {
  color: #333;
  font-size: 17px;
  font-weight: 600;
}

.van-nav-bar :deep(.van-icon) {
  color: #333;
}

.profile-card {
  background: #fff;
  border-radius: 24px;
  margin: 24px 12px;
  padding: 32px 18px 18px 18px;
  box-shadow: 0 2px 16px #ece8ff44;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.avatar-center {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 18px;
}
.avatar-img {
  width: 90px;
  height: 90px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e0e0e0;
  box-shadow: 0 2px 8px #e0e0e0;
}
.avatar-placeholder {
  width: 90px;
  height: 90px;
  border-radius: 50%;
  background: #f0f0f0;
  color: #bbb;
  font-size: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px dashed #e0e0e0;
}
.avatar-uploader-btn {
  margin-top: 8px;
}
.avatar-upload-btn {
  border-radius: 18px;
  font-size: 15px;
  padding: 0 22px;
  background: #a48fff;
  border: none;
}
.profile-field {
  width: 100%;
  margin-bottom: 18px;
}
.field-label {
  font-size: 16px;
  color: #222;
  margin-bottom: 8px;
  font-weight: 500;
}
.gender-card-group {
  display: flex;
  gap: 18px;
  margin-bottom: 4px;
}
.gender-card {
  flex: 1;
  background: #f3edff;
  border-radius: 16px;
  padding: 16px 0;
  text-align: center;
  font-size: 18px;
  color: #a48fff;
  border: 2px solid transparent;
  cursor: pointer;
  transition: all 0.2s;
  user-select: none;
  position: relative;
}
.gender-card.selected {
  background: #a48fff;
  color: #fff;
  border-color: #a48fff;
}
.gender-card.locked {
  opacity: 0.6;
  pointer-events: none;
}
.gender-icon {
  font-size: 26px;
  display: block;
  margin-bottom: 2px;
}
.gender-tip {
  font-size: 13px;
  color: #aaa;
  margin-top: 2px;
}
.save-btn {
  background: #a48fff;
  border-radius: 22px;
  margin-top: 24px;
  font-size: 18px;
  font-weight: bold;
  height: 48px;
}

.loading-overlay {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.9);
}

.loading-card {
  background: #fff;
  border-radius: 24px;
  padding: 32px;
  box-shadow: 0 8px 24px rgba(164, 143, 255, 0.15);
  display: flex;
  flex-direction: column;
  align-items: center;
  animation: cardAppear 0.3s ease-out;
}

.loading-icon {
  margin-bottom: 16px;
}

.loading-text {
  font-size: 16px;
  color: #7062c1;
  font-weight: 500;
}

@keyframes cardAppear {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

:deep(.van-overlay) {
  z-index: 2000;
}
</style>